package com.smbms.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.smbms.entity.SmbmsUser;
import com.smbms.entity.page.Page;
import com.smbms.mapper.SmbmsUserMapper;
import com.smbms.service.UserService;

@Transactional
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	SmbmsUserMapper userMapper;

	@CachePut(cacheNames = "user", key = "#user.id")
	public int updateUser(SmbmsUser user) {
		return userMapper.updateByPrimaryKey(user);
	}

	@CachePut(cacheNames = "user", key = "#user.id")
	public int addUser(SmbmsUser user) {
		return userMapper.insert(user);
	}

	public SmbmsUser login(String userCode, String userPassword) {
		return userMapper.login(userCode, userPassword);
	}

	@Cacheable(cacheNames = "userList", key = "#pageNo")
	public Page<SmbmsUser> selectUserByPage(String userName, Integer userRole, Integer pageNo, Integer pageSize) {

		Page<SmbmsUser> page = new Page<SmbmsUser>(pageNo, pageSize);
		page.setTotalRow(userMapper.selectUserByPageCount(userName, userRole));
		page.setList(
				userMapper.selectUserByPage(userName, userRole, (pageNo - 1) * page.getPageSize(), page.getPageSize()));
		return page;
	}

	@Cacheable(cacheNames = "user", key = "#id")
	public SmbmsUser getUserById(Long id) {
		return userMapper.selectByPrimaryKey(id);
	}

	public int checkUserCode(String userCode) {
		return userMapper.checkUserCode(userCode);
	}

	public SmbmsUser findByUsername(String username) {

		return userMapper.findByUsername(username);
	}

	public Set<String> findRoles(String username) {

		Set<String> sets = new HashSet<>();
		sets.add(userMapper.findRoles(username));

		return sets;
	}

	public Set<String> findPermissions(String username) {
		return userMapper.findPermissions(username);
	}

}
